import React from 'react';
import { Box, Drawer, Fade, Slide, AppBar, Toolbar, styled, useMediaQuery, useTheme } from '@mui/material';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from "contexts/AuthContext";
import { getHomeType } from 'utils/common';
import PortalCloseButton from 'components/atoms/PortalCloseButton';
import { HomePageContent, AdminContent, UserContent } from './DrawerContent';

// Styled AppBar component with conditional background based on route
const StyledAppBar = styled(AppBar)(({ isHomePage }) => ({
  position: isHomePage ? 'fixed' : 'sticky',
  top: 0,
  left: 0,
  right: 0,
  zIndex: 1200,
  visibility: 'visible !important',
  transform: 'none !important',
  background: 'none !important',
  backgroundColor: 'none !important',
  boxShadow: 'none !important',
  backdropFilter: 'none !important',
  marginTop: 0,
}));

// Styled Toolbar for both light and dark modes - matching the one from TopIcons
const StyledToolbar = styled(Toolbar)(({ theme, darkMode }) => ({
  padding: '8px 16px',
  margin: 0,
  width: '100%',
  justifyContent: 'space-between',
  alignItems: 'center',
  borderRadius: '10px',
  transition: 'all 0.3s ease',
  
  // Light Mode (Neumorphic)
  ...(!darkMode && { 
    backgroundColor: 'transparent',
    boxShadow: 'inset 2px 2px 5px rgba(223, 227, 238, 0.8), inset -2px -2px 5px rgba(255, 255, 255, 0.9)'
  }),
  
  // Dark Mode (TreeItems styling with black and dark cyan)
  ...(darkMode && {
    backgroundColor: 'transparent !important',
    background: 'linear-gradient(145deg, rgba(0, 10, 15, 0.9), rgba(0, 0, 0, 0.85))',
    boxShadow: 'inset 1px 1px 2px rgba(0, 0, 0, 0.4), inset -1px -1px 2px rgba(0, 255, 242, 0.08)',
  })
}));

const DashboardDrawer = ({ open, toggleDashboardDrawer, darkMode = false, placeBefore = false, layout = '' }) => {
  const navigate = useNavigate();
  const location = useLocation();
  
  // Safely destructure user with a default empty object
  const { user = {} } = useAuth();
  
  const theme = useTheme();
  const isSmUp = useMediaQuery(theme.breakpoints.up('sm')); // Checks if width is 600px or larger
  
  // Get isHomePage from utils/common.js - using getHomeType instead of getPageTypes
  const isHomePage = getHomeType(location.pathname);
  
  // eslint-disable-next-line
  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const navigateOpen = (path) => {
    if (path === 'toggleDashboardDrawer') {
      toggleDashboardDrawer();
    } else {
      navigate(path);
      // Only close drawer if not in permanent mode
      if (!isSmUp) {
        toggleDashboardDrawer();
      }
    }
  };
  
  // Determine which content to render
  const renderContent = (isXs) => {
    if (isHomePage) {
      return <HomePageContent 
        isXs={isXs}
        placeBefore={placeBefore}
        darkMode={darkMode}
        navigateOpen={navigateOpen}
        navigatePage={navigatePage}
        layout={layout}
      />;
    } else if (user && user.role && (user.role === "admin" || user.role === "superadmin")) {
      return <AdminContent 
        isXs={isXs}
        placeBefore={placeBefore}
        darkMode={darkMode}
        navigateOpen={navigateOpen}
        navigatePage={navigatePage}
        layout={layout}
      />;
    } else {
      // For UserContent, set placeBefore to true for desktop (!isXs) and false for mobile (isXs)
      const userContentPlaceBefore = !isXs;
      return <UserContent 
        isXs={isXs}
        placeBefore={userContentPlaceBefore}
        darkMode={darkMode}
        navigateOpen={navigateOpen}
        navigatePage={navigatePage}
        layout={layout}
      />;
    }
  };
  
  // Main drawer component with responsive behavior
  return (
    <>
      {isSmUp ? (
        // Permanent sidebar for larger screens - minimal styling with flex properties
        <Box sx={{
          borderRight: darkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(0,0,0,0.1)',
          backgroundColor: darkMode ? '#000' : '#fff',
          padding: 0,
          margin: 0,
          // Add flex properties to the Box containing renderContent
          display: 'flex',
          flexDirection: 'column',
          width: '100%'
        }}>
          {renderContent(false)} {/* Pass false for desktop view */}
        </Box>
      ) : (
        // Temporary drawer for mobile screens - original styling
        <Drawer
          anchor="left"
          open={open}
          onClose={() => toggleDashboardDrawer(false)}
          variant="temporary"
          TransitionComponent={isHomePage ? Fade : Slide}
          PaperProps={{
            sx: {
              zIndex: 9999,
              height: '100vh',
              width: isHomePage ? '100vw' : 'auto',
              borderRadius: 0,
              backgroundColor: darkMode ? '#000' : '#fff',
              background: darkMode ? '#000' : '#fff',
            },
          }}
        >
          <StyledAppBar isHomePage={isHomePage}>
            {/* Using StyledToolbar instead of regular Toolbar */}
            <StyledToolbar 
              disableGutters
              darkMode={darkMode}
              sx={{
                maxWidth: {
                  xs: '100%',
                  sm: '600px',
                  md: '960px',
                  lg: '1280px',
                  xl: '1920px'
                },
                mx: 'auto',
                background: 'none !important',
                backgroundColor: 'none !important',
                boxShadow: 'none !important',
                backdropFilter: 'none !important'
              }}
            >
              {/* Spacer element to match the LogoComponent in TopIcons */}
              <Box sx={{ visibility: 'hidden', width: '200px' }}></Box>
              
              {/* Close button container - now matches the Hamburger button */}
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <PortalCloseButton
                  onClick={() => toggleDashboardDrawer(false)}
                  id="close-drawer-button"
                  className="drawer-close-button"
                  darkMode={darkMode}
                  style={{ marginTop: 5 }}
                  aria-label="Close"
                />
              </Box>
            </StyledToolbar>
          </StyledAppBar>
          <Box sx={{ 
            p: 3, 
            pt: 10 
          }}>
            {renderContent(true)} {/* Pass true for mobile view */}
          </Box>
        </Drawer>
      )}
    </>
  );
};

export default DashboardDrawer;